const cloud = require('wx-server-sdk');
const xlsx = require('node-xlsx')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

// 创建集合云函数入口函数
exports.main = async (event, context) => {
    try {
        // 请求参数
        let {
            conditions
        } = event.data

        if (typeof conditions == "string") {
            // 未传递筛选条件时 conditions会默认等于"1"
            conditions = {}
        }

        // 构建查询条件
        let query = db.collection("goodsList")
        // 文件名称
        let fileName = `商品列表${new Date().getTime()}.xlsx`

        query = query.where(conditions) // 添加筛选条件
        query = query.orderBy('createTime', 'desc') // 排序

        // 导出数据
        const consumeRecord = await query.get()

        if (consumeRecord.data.length <= 0) {
            return {
                code: 401,
                msg: "暂无商品",
            }
        }

        let excelData = []
        let header = []
        header = ['分类', '子分类', '商品名称', '规格', '单位', '市场价', '平台价', '活动价', '金豆价', '商品属性', '是否允许快递自提抵扣', '是否参与商品折扣', '是否允许累计积分折扣', '是否参与分销提成机制', '分销提成方案', '是否参与三级共创奖励', '奖励规则名称', '创建时间']
        excelData.push(header)
        consumeRecord.data.forEach(item => {
            let row = []
            row.push(item.categoryName)
            row.push(item.childCategoryName)
            row.push(item.goodsName)
            row.push(item.goodsSize)
            row.push(item.goodsUnit)
            row.push(item.marketPrice)
            row.push(item.platformPrice)
            row.push(item.activityPrice)
            row.push(item.goldPeaPrice)
            row.push(item.goodsType)
            row.push(item.isExpressDiscount == '1' ? '是' : '否')
            row.push(item.isGoodsDiscount == '1' ? '是' : '否')
            row.push(item.isIntegralDiscount == '1' ? '是' : '否')
            row.push(item.isDistribution == '1' ? '是' : '否')
            row.push(item.distribution)
            row.push(item.isThreeLevelAward == '1' ? '是' : '否')
            row.push(item.rewardRule)
            row.push(item.createTime)
            excelData.push(row)
        })

        let buffer = xlsx.build([{
            name: fileName,
            data: excelData
        }]);

        //上传到云存储
        const fileData = await cloud.uploadFile({
            cloudPath: `xlsx/${fileName}`,
            fileContent: buffer
        })

        return {
            code: 200,
            msg: "操作成功",
            data: fileData.fileID,
        }
    } catch (err) {
        console.log("err----", err)
    }
};